#include "pd_accepter.h"
#include "pd_log.h"
#include "pd_tcp_ioc.h"
#include "pd_transport.h"

void pd_listenfd_on_readable(PdIOComponent *ioc)
{
    PdSocket *accept_sock = NULL;
    PdIOComponent *accept_ioc = NULL;
    if (NULL == ioc)
    {
        PD_LOG(WARN, "ioc null pointer");
    }
    else if (NULL == ioc->sock)
    {
        PD_LOG(WARN, "sock null pointer");
    }
    else if (NULL == ioc->ts)
    {
        PD_LOG(WARN, "ts null pointer");
    }
    else if (NULL == (accept_sock = pd_socket_accept_tcp_client(ioc->sock)))
    {
        PD_LOG(WARN, "accept sock fail, listen_sock=%p", ioc->sock);
    }
    else if (NULL == (accept_ioc = pd_ioc_alloc()))
    {
        PD_LOG(WARN, "alloc ioc fail, accept_sock=%p", accept_sock);
        pd_socket_destroy(accept_sock);
    }
    else
    {
        accept_ioc->sock = accept_sock;
        accept_ioc->ts = ioc->ts;
        accept_ioc->on_readable = pd_tcpfd_on_readable;
        accept_ioc->on_writeable = pd_tcpfd_on_writeable;
        accept_ioc->on_error = pd_tcpfd_on_error;
        if (0 != pd_transport_add_ioc(accept_ioc->ts, accept_ioc, 1, 0))
        {
            PD_LOG(WARN, "pd_transport_add_ioc fail, accept_ioc=%p", accept_ioc);
            pd_socket_destroy(accept_sock);
            pd_ioc_free(accept_ioc);
        }
    }
}

void pd_listenfd_on_writeable(PdIOComponent *ioc)
{
    PD_LOG(FATAL, "unexpected error, listen fd cannot be writeable, ioc=%p", ioc);
}

void pd_listenfd_on_error(PdIOComponent *ioc)
{
    if (NULL == ioc)
    {
        PD_LOG(WARN, "ioc null pointer");
    }
    else if (NULL == ioc->sock)
    {
        PD_LOG(WARN, "sock null pointer");
    }
    else if (NULL == ioc->ts)
    {
        PD_LOG(WARN, "ts null pointer");
    }
    else if (0 == pd_transport_remove_ioc(ioc->ts, ioc))
    {
        PD_LOG(WARN, "pd_transport_remove_ioc fail, ioc=%p", ioc);
    }
    else
    {
        PD_LOG(WARN, "listen fd error, will close, ioc=%p sock=%p", ioc, ioc->sock);
        pd_socket_destroy(ioc->sock);
        pd_ioc_free(ioc);
    }
}

